package com.xj.openapi4j.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.xj.openapi4j.commons.TokenManager;
import  com.xj.openapi4j.exception.OpenAPIException;
import com.xj.openapi4j.service.token.U8Token;
import  com.xj.openapi4j.util.HttpUtil;
import com.xj.openapi4j.util.RequestTool;
import com.xj.util.Constance;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 人员信息
 */

@Service
@Slf4j
public class PersonService {
	@Value("${u8AppKey}")
	String u8AppKey;

	@Value("${u8AppSecret}")
	String u8AppSecret;
	@Value("${fromAccount}")
	String from_account;

	@Autowired
	U8Token u8Token;
	@Autowired
	RedisTemplate redisTemplate;




	public JSONObject getPersonInfo(String name) throws Exception {
		Object  customerInfo=redisTemplate.opsForHash().get(Constance.person,name);
		if(customerInfo==null) {
			String url = "https://api.yonyouup.com/api/person/batch_get";
			Map<String, String> paramMap = new HashMap();
			paramMap.put("from_account", from_account);
			paramMap.put("to_account", from_account);
			paramMap.put("name", name);
			paramMap.put("app_key", u8AppKey);
			paramMap.put("token", u8Token.getToken());
			String str = RequestTool.doGet(url, paramMap);
			JSONObject jsonObject = JSONObject.parseObject(str);
			if("0".equals(jsonObject.getString("errcode"))){
				JSONArray jsonArray=jsonObject.getJSONArray("person");
				JSONObject data=jsonArray.getJSONObject(0);
				redisTemplate.opsForHash().put(Constance.person, name, data);
				return data;
			}
		}else {
			return  (JSONObject) customerInfo;
		}
		return null;
	}



}
